package com.unibuy.smartdevice.ui.dialog;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;

import com.unibuy.smartdevice.DialogAbstract;
import com.unibuy.smartdevice.HomeActivity;
import com.unibuy.smartdevice.MyApp;
import com.unibuy.smartdevice.R;
import com.unibuy.smartdevice.databinding.DialogAccessCodeBinding;
import com.unibuy.smartdevice.databinding.DialogPickupCodeFontendBinding;
import com.unibuy.smartdevice.devices.DeviceType;
import com.unibuy.smartdevice.devices.SlotField;
import com.unibuy.smartdevice.devices.UsbDev;
import com.unibuy.smartdevice.exception.LogsEmptyException;
import com.unibuy.smartdevice.exception.LogsIOException;
import com.unibuy.smartdevice.exception.LogsParseException;
import com.unibuy.smartdevice.exception.LogsSettingEmptyException;
import com.unibuy.smartdevice.exception.LogsUnsupportedOperationException;
import com.unibuy.smartdevice.external.HttpAPI;
import com.unibuy.smartdevice.structure.BuyStructure;
import com.unibuy.smartdevice.structure.ProductStructure;
import com.unibuy.smartdevice.structure.SlotStructure;
import com.unibuy.smartdevice.tools.HandlerMain;
import com.unibuy.smartdevice.tools.HandlerMainCountdown;
import com.unibuy.smartdevice.tools.HandlerMainScheduler;
import com.unibuy.smartdevice.tools.ToastHandlerMain;
import com.unibuy.smartdevice.tools.Tools;
import com.unibuy.smartdevice.ui.FontendActivity;

import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;

public class FontendPickupCodeDialog extends DialogAbstract {
    public enum Option {
        TOAST(0),
        COUNTDOWN_CANCEL(1),
        SET_COUNTDOWN_TEXT(2),
        INVOICE_SUCCESSFUL(4),
        INVOICE_FAILED(5),
        CHANGE_DISPATCH(6),
        CHANGE_BUY(7),
        SET_STATUS_TEXT(8),
        ;

        private int option;

        public int getOption() {
            return option;
        }

        Option(int option) {
            this.option = option;
        }
    }

    public static final Map<Integer, Option> optionMap = new HashMap<>();
    static {
        for (Option option : Option.values()) {
            optionMap.put(option.getOption(), option);
        }
    }

    @Override
    protected Context setCtx() {
        return getContext();
    }

    @Override
    protected Class<? extends DialogAbstract> setCls() {
        return getClass();
    }

    @Override
    protected HandlerMain setHandlerMain() {
        return new ToastHandlerMain(getCtx(), getLogs()) {
            @Override
            protected void execute(Context context, int commandCode, String message) {
                Option option = optionMap.get(commandCode);

                switch (option) {
                    case TOAST:
                        super.execute(context, commandCode, message);
                        break;
                    case COUNTDOWN_CANCEL:
                        cancelOnThreadCountdown();
                        break;
                    case SET_COUNTDOWN_TEXT:
                        setButtonCancelText(Integer.valueOf(message));
                        break;
                    case INVOICE_SUCCESSFUL:
                        MyApp.getInstance().getInvoiceData().setCarrier(message);
                        MyApp.getInstance().getReportFlowInfoData().setInvoiceInfo("carrier:" + MyApp.getInstance().getInvoiceData().getCarrier());
                        break;
                    case INVOICE_FAILED:
                        break;
                    case CHANGE_DISPATCH:
                        //reportAccessCodeData();//上傳通行碼資訊到後台系統
                        changeDispatch();
                        break;
                    case CHANGE_BUY:
                        try {
                            /*  這裡判斷 取貨碼要取貨時，若前面貨道沒商品，就先找其他貨道確認有無該商品，若有則出貨，否則就是提示該商品已無庫存   */
                            int changebuyslot = 0; //要出貨的格子櫃號號碼
                            for(int j = 0; j < MyApp.getInstance().getSlotList(2).size();j++) {
                                /* 這裡判斷邏輯是以通行碼要出貨的鮮花機內的商品ID去跟目前格子櫃上商品做判斷，假設格子櫃上有3個同樣的商品。
                                 * 若第一個已經出貨，接著判斷下一個同樣的商品還未出貨的，取出它的貨道號碼(格子櫃號)，作為要出貨的貨道號碼(格子櫃號)*/
                                if(MyApp.getInstance().getSlotList(2).get(j).getProduct().getProductID().equals(message) && MyApp.getInstance().getSlotList(2).get(j).getCount() > 0){
                                    changebuyslot = MyApp.getInstance().getSlotList(2).get(j).getSlot();
                                    break;
                                }
                            }
                            /*這裡判斷 取貨碼要取貨時，若前面貨道沒商品，就先找其他貨道確認有無該商品，若有則出貨，否則就是提示該商品已無庫存*/
                            SlotStructure slotProduct = MyApp.getInstance().getSlotDataByPid(message);

                            SlotField slotField = SlotField.getSlotField(slotProduct.getField());
                            switch (slotField) {
                                case FLOWER:
                                    if (slotProduct.isLock()) {
                                        getSrcHandlerMain().start("FontendPickupCodeDialog", "@"+getContext().getString(R.string.product_sales_suspended));//商品暫停販售
                                        dialogCancel();
                                    } else if (slotProduct.getCount() == 0) {
                                        getSrcHandlerMain().start("FontendPickupCodeDialog", "@"+getContext().getString(R.string.product_out_of_stock));//商品無存貨
                                        dialogCancel();
                                    }

                                    if(changebuyslot >0){
                                        BuyStructure buyProduct = new BuyStructure(slotProduct.getField(), changebuyslot, slotProduct.getProduct(), 1);
                                        MyApp.getInstance().getBuyList().add(buyProduct);
                                        changeBuy();
                                    }else{
                                        dialogCancel();
                                        new PickupFlowerDialog(context,getSrcHandlerMain()).show();
                                        getLogs().info("該商品無庫存，請確認有庫存再來取貨! ProductID="+message);
                                    }

                                    break;
                                case ELECTRIC:
                                    if (slotProduct.isLock())
                                        MyApp.getInstance().getSlotDataByPid(message).setLock(false);

                                    getSrcHandlerMain().start("FontendPickupCodeDialog", "@"+getContext().getString(R.string.unlock) + slotProduct.getProduct().getProductName());//解鎖
                                    getSrcHandlerMain().start("FontendPickupCodeDialog", FontendActivity.Option.RESET_DATA.getOption(), "reset data");
                                    dialogCancel();

                                    break;
                            }
                        } catch (LogsEmptyException e) {
                            setStatusText(getContext().getString(R.string.product_not_found));//找不到商品
                        }
                        break;
                    case SET_STATUS_TEXT:
                        setStatusText(message);
                        break;
                }
            }
        };
    }

    private DialogPickupCodeFontendBinding binding;
    private CloseDialogOnThreadHandler closeDialogCountdown;
    private boolean isChangeDispatch;
    private boolean openBarcode;
    private HttpAPI httpAPI;

    public FontendPickupCodeDialog(Context context, HandlerMain srcHandlerMain) {
        super(context, srcHandlerMain);
    }

    @Override
    protected void onCreate(Context context) {
        binding = DialogPickupCodeFontendBinding.inflate(getLayoutInflater());
        setContentView(binding.getRoot());

        MyApp.getInstance().initialReportData();

        isChangeDispatch = true;
        openBarcode = true;
        httpAPI = new HttpAPI(getHandlerMain());

        binding.buttonFinish.setOnClickListener(v -> changeOk());
        binding.buttonCancel.setOnClickListener(v -> changeBuy());

        closeDialogCountdown = new CloseDialogOnThreadHandler(getHandlerMain());
        closeDialogCountdown.start(40);

        binding.buttonR1.setOnClickListener(v -> {
            String text = binding.editTextNumber.getText().toString();
            binding.editTextNumber.setText(text.substring(0, text.length()-1));
            binding.editTextNumber.setSelection(binding.editTextNumber.getText().length());
            closeDialogCountdown.setCountdown(40);
        });

        binding.buttonC1.setOnClickListener(v -> {
            binding.editTextNumber.setText("");
            closeDialogCountdown.setCountdown(40);
        });

        binding.button10.setOnClickListener(v -> {
            String btnName = binding.button10.getText().toString();
            String text = binding.editTextNumber.getText().toString();
            binding.editTextNumber.setText(text+btnName);
            binding.editTextNumber.setSelection(binding.editTextNumber.getText().length());
            closeDialogCountdown.setCountdown(40);
        });

        binding.button11.setOnClickListener(v -> {
            String btnName = binding.button11.getText().toString();
            String text = binding.editTextNumber.getText().toString();
            binding.editTextNumber.setText(text+btnName);
            binding.editTextNumber.setSelection(binding.editTextNumber.getText().length());
            closeDialogCountdown.setCountdown(40);
        });

        binding.button12.setOnClickListener(v -> {
            String btnName = binding.button12.getText().toString();
            String text = binding.editTextNumber.getText().toString();
            binding.editTextNumber.setText(text+btnName);
            binding.editTextNumber.setSelection(binding.editTextNumber.getText().length());
            closeDialogCountdown.setCountdown(40);
        });

        binding.button13.setOnClickListener(v -> {
            String btnName = binding.button13.getText().toString();
            String text = binding.editTextNumber.getText().toString();
            binding.editTextNumber.setText(text+btnName);
            binding.editTextNumber.setSelection(binding.editTextNumber.getText().length());
            closeDialogCountdown.setCountdown(40);
        });

        binding.button14.setOnClickListener(v -> {
            String btnName = binding.button14.getText().toString();
            String text = binding.editTextNumber.getText().toString();
            binding.editTextNumber.setText(text+btnName);
            binding.editTextNumber.setSelection(binding.editTextNumber.getText().length());
            closeDialogCountdown.setCountdown(40);
        });

        binding.button15.setOnClickListener(v -> {
            String btnName = binding.button15.getText().toString();
            String text = binding.editTextNumber.getText().toString();
            binding.editTextNumber.setText(text+btnName);
            binding.editTextNumber.setSelection(binding.editTextNumber.getText().length());
            closeDialogCountdown.setCountdown(40);
        });

        binding.button16.setOnClickListener(v -> {
            String btnName = binding.button16.getText().toString();
            String text = binding.editTextNumber.getText().toString();
            binding.editTextNumber.setText(text+btnName);
            binding.editTextNumber.setSelection(binding.editTextNumber.getText().length());
            closeDialogCountdown.setCountdown(40);
        });

        binding.button17.setOnClickListener(v -> {
            String btnName = binding.button17.getText().toString();
            String text = binding.editTextNumber.getText().toString();
            binding.editTextNumber.setText(text+btnName);
            binding.editTextNumber.setSelection(binding.editTextNumber.getText().length());
            closeDialogCountdown.setCountdown(40);
        });

        binding.button18.setOnClickListener(v -> {
            String btnName = binding.button18.getText().toString();
            String text = binding.editTextNumber.getText().toString();
            binding.editTextNumber.setText(text+btnName);
            binding.editTextNumber.setSelection(binding.editTextNumber.getText().length());
            closeDialogCountdown.setCountdown(40);
        });

        binding.button19.setOnClickListener(v -> {
            String btnName = binding.button19.getText().toString();
            String text = binding.editTextNumber.getText().toString();
            binding.editTextNumber.setText(text+btnName);
            binding.editTextNumber.setSelection(binding.editTextNumber.getText().length());
            closeDialogCountdown.setCountdown(40);
        });

        new ReadBarCodeOnScheduler(getHandlerMain()).start(5, TimeUnit.SECONDS);
    }

    public class ReadBarCodeOnScheduler extends HandlerMainScheduler {
        public ReadBarCodeOnScheduler(HandlerMain handlerMain) {
            super(handlerMain);
        }

        @Override
        protected HandlerMain setHandlerMain() {
            return getSrcHandlerMain();
        }

        @Override
        protected void execute(HandlerMain handlerMain) {
            try {
                int totalPrice = 0;
                for (BuyStructure buy : MyApp.getInstance().getBuyList()) {
                    totalPrice += buy.getFullPrice();
                }

                UsbDev usbDev = new UsbDev(DeviceType.QRCODE_SCANNER);
                byte[] buffer = new byte[1000];
                usbDev.read(buffer, 100);
                for (int i=0; i<7; i++) {
                    if (isRun() && openBarcode) {
                        int size = usbDev.read(buffer, 5000);
                        if (size > 5) {
                            String barCodeString = new String(buffer, 0, size);
                            getHandlerMain().start(getLogs().getClassName(), getCtx().getString(R.string.receive_barcode)+"："+ Tools.randomReplace(barCodeString, 0.3)+"，"+getCtx().getString(R.string.send_transaction));//收到條碼,送出交易

                            try {
                                MyApp.getInstance().getMemberVerificationStructure().setProductId("0");
                                MyApp.getInstance().getMemberVerificationStructure().setProductPrice(0);
                                MyApp.getInstance().getMemberVerificationStructure().setMemberBarCode(barCodeString);
                                MyApp.getInstance().getMemberVerificationStructure().setVerificationType(2);
                                httpAPI.memberVerification(MyApp.getInstance().getMemberVerificationStructure());
                            } catch (LogsParseException | LogsSettingEmptyException e) {
                                getLogs().warning(e);
                            }

                            openBarcode = false;
                        }
                    }
                }
                usbDev.closePort();
            } catch (LogsUnsupportedOperationException | LogsIOException | LogsEmptyException e) {
                getLogs().warning(e);
            }
        }

        @Override
        protected Class<?> setCls() {
            return getClass();
        }
    }

    public int getTotalPrice() {
        int totalPrice = 0;
        if (MyApp.getInstance().getBuyList().size() == 0) return totalPrice;
        for(BuyStructure buy: MyApp.getInstance().getBuyList()) {
            totalPrice += buy.getFullPrice();
        }
        return totalPrice;
    }

    public void changeDispatch() {
        if (isChangeDispatch) {
            closeDialogCountdown.shutdown();
            isChangeDispatch = false;
//            changeDialog(DispatchDialog.class);
            changeDialog(FlowerPickupDialog.class);
        }
    }

    public void changeOk() {
        try {
            String number = binding.editTextNumber.getText().toString();
            MyApp.getInstance().getMemberVerificationStructure().setProductId("0");
            MyApp.getInstance().getMemberVerificationStructure().setProductPrice(0);
            MyApp.getInstance().getMemberVerificationStructure().setMemberBarCode(number);
            MyApp.getInstance().getMemberVerificationStructure().setVerificationType(2);
            httpAPI.memberVerification(MyApp.getInstance().getMemberVerificationStructure());
        } catch (LogsParseException e) {
            throw new RuntimeException(e);
        } catch (LogsSettingEmptyException e) {
            throw new RuntimeException(e);
        }
    }

    public void changeBuy() {
        closeDialogCountdown.shutdown();
        BuyPickupCodeDialog buyDialog = new BuyPickupCodeDialog(getContext(), getSrcHandlerMain());
        buyDialog.show();
        cancel();
    }

    public void dialogCancel() {
        closeDialogCountdown.shutdown();
        MyApp.getInstance().getBuyList().clear();
        cancel();
    }

    public void cancelOnThreadCountdown() {
        MyApp.getInstance().getBuyList().clear();
        cancel();
    }

    public void setButtonCancelText(long countdown) {
        binding.buttonCancel.setText(getContext().getString(R.string.return_to)+"("+countdown+")");//返回
    }

    public void setStatusText(String message) {
        binding.textStatus.setText(message);
    }

    public void reportAccessCodeData()  {
        try {
            MyApp.getInstance().getReportAccessCodeStructure().setField(MyApp.getInstance().getReportAccessCodeStructure().getField());
            MyApp.getInstance().getReportAccessCodeStructure().setSlot(MyApp.getInstance().getBuyList().get(0).getSlot());
            MyApp.getInstance().getReportAccessCodeStructure().setProductId(MyApp.getInstance().getReportAccessCodeStructure().getProductId());
            httpAPI.reportAccessCode(MyApp.getInstance().getReportAccessCodeStructure());
        } catch (LogsParseException e) {
            throw new RuntimeException(e);
        } catch (LogsSettingEmptyException e) {
            throw new RuntimeException(e);
        }
    }

    public void updatePickupCodeData()  {
        try {
            String number = binding.editTextNumber.getText().toString();
            MyApp.getInstance().getMemberVerificationStructure().setProductId("0");
            MyApp.getInstance().getMemberVerificationStructure().setProductPrice(0);
            MyApp.getInstance().getMemberVerificationStructure().setMemberBarCode(number);
            MyApp.getInstance().getMemberVerificationStructure().setVerificationType(2);
            httpAPI.memberVerification(MyApp.getInstance().getMemberVerificationStructure());
        } catch (LogsParseException e) {
            throw new RuntimeException(e);
        } catch (LogsSettingEmptyException e) {
            throw new RuntimeException(e);
        }
    }

    public static class CloseDialogOnThreadHandler extends HandlerMainCountdown {
        public CloseDialogOnThreadHandler(HandlerMain handlerMain) {
            super(handlerMain);
            handlerMain.start(getClass().getSimpleName(), CheckoutCashDialog.Option.SET_COUNTDOWN_TEXT.getOption(), String.valueOf(getSrcCountdown()));
        }

        @Override
        protected HandlerMain setHandlerMain() {
            return getSrcHandlerMain();
        }

        @Override
        protected void close(HandlerMain handlerMain) {
            handlerMain.start(getClass().getSimpleName(), BuyDialog.Option.COUNTDOWN_CANCEL.getOption(), "close dialog");
        }

        @Override
        protected void execute(long countdown, HandlerMain handlerMain) {
            handlerMain.start(getClass().getSimpleName(), BuyDialog.Option.SET_COUNTDOWN_TEXT.getOption(), String.valueOf(countdown));
        }

        @Override
        protected Class<?> setCls() {
            return getClass();
        }
    }
}
